--- lua-resty-mysql
--- https://github.com/openresty/lua-resty-mysql

local mysql = require "resty.mysql"
local db, err = mysql:new()
if not db then
    ngx.say("failed to instantiate mysql: ", err)
    return
end

db:set_timeout(1000) -- 1 sec

local ok, err, errcode, sqlstate = db:connect {
    host = "192.168.248.136",
    port = 3306,
    database = "hc",
    user = "hc",
    password = "Password",
    charset = "utf8",
    max_packet_size = 1024 * 1024,
}

ngx.say("connected to mysql.<br/>")

local res, err, errcode, sqlstate = db:query("drop table if exists cats")
if not res then
    ngx.say("bad result: ", err, "; ", errcode, "; ", sqlstate, ".")
    return
end

res, err, errcode, sqlstate = db:query("create table cats"
        .. "(id serial primary key,"
        .. "name varchar(5))")
if not res then
    ngx.say("bad result: ", err, "; ", errcode, "; ", sqlstate, ".")
    return
end

ngx.say("table cats created.")

res, err, errcode, sqlstate = db:query("select * from student")
if not res then
    ngx.say("bad result: ", err, "; ", errcode, "; ", sqlstate, ".")
    return
end

local cjson = require "cjson"
ngx.say("bad result: ", cjson.encode(res))

ok, err = db:set_keepalive(10000, 100)
if not ok then
    ngx.say("failed to set keepalive: ", err)
    return
end

